<template>
  <div class="menu-form">
    <el-dialog
      title="编辑菜单"
      :visible.sync="dialog"
      width="40%"
      @close="handleClose"
    >

      <el-form ref="form" :model="menu" :rules="rules" label-width="80px" :inline="false" size="normal">
        <el-form-item label="菜单类型">
          <el-radio-group v-model="menuType">
            <el-radio key="1" :label="1">顶级目录</el-radio>
            <el-radio key="2" :label="2">菜单</el-radio>
            <el-radio key="3" :label="3">按钮</el-radio>
          </el-radio-group>

        </el-form-item>

        <el-form-item v-show="menuType!=1" label="上级菜单">
          <el-cascader
            ref="menuTree"
            v-model="menu.pId"
            :options="optionsCom"
            size="small"
            :props="{ expandTrigger: 'hover', emitPath: false, checkStrictly: true , label: 'title', value: 'id' }"
            clearable
            @change="menuTreeChange"
          />
        </el-form-item>
        <el-form-item v-if="menuType!=3" label="路由名称" prop="name">
          <el-input v-model="menu.name" size="small" placeholder="前端路由name,唯一" />
        </el-form-item>
        <el-form-item v-if="menuType==3" label="按钮名称" prop="title">
          <el-input v-model="menu.title" size="small" placeholder="按钮名称,比如: 新增" />
        </el-form-item>
        <el-form-item v-if="menuType!=3" label="路径" prop="path">
          <el-input v-model="menu.path" size="small" placeholder="前端路由path,忽略父节点路径" />
        </el-form-item>
        <el-form-item v-if="menuType!=3" label="组建路径" prop="component">
          <el-input v-model="menu.component" size="small" placeholder="前端路由组件路径,比如@/views/foo/foo.vue" />
        </el-form-item>
        <el-row :gutter="30">
          <el-col :span="8" :offset="0">
            <el-form-item label="排序">
              <el-input-number v-model.number="menu.sort" size="small" placeholder="排序:值越大,越靠前" />
            </el-form-item>
          </el-col>
          <el-col :span="16" :offset="0">
            <el-form-item v-if="menuType==1" label="重定向">
              <el-input v-model.number="menu.redirect" size="small" placeholder="redirect属性" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item v-if="menuType!=3" label="是否显示">
              <el-select v-model="menu.hidden" size="small" value-key="" placeholder="hidden属性" clearable filterable>
                <el-option
                  label="否"
                  :value="0"
                />
                <el-option
                  label="是"
                  :value="1"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" :offset="0">
            <el-form-item v-if="menuType!=3" label="是否展开">
              <el-select v-model="menu.alwaysShow" size="small" value-key="" placeholder="alwaysShow属性" clearable filterable>
                <el-option
                  label="否"
                  :value="0"
                />
                <el-option
                  label="是"
                  :value="1"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item v-if="menuType!=3" label="meta属性" size="normal">
          <el-row v-for="meta in metaList" :key="meta.tempId" style="margin-left:0" :gutter="30">
            <el-col style="padding-left:0" :span="9">
              <el-input v-model="meta.key" placeholder="比如: title" size="mini" clearable />
            </el-col>
            <el-col :span="9" :offset="0">
              <el-input v-model="meta.value" placeholder="比如: 商品管理" size="mini" clearable />
            </el-col>
            <el-col :span="6" :offset="0">
              <el-button type="text" size="mini" icon="el-icon-plus" @click="createMetaItem" />
              <el-button type="text" style="color:red;" size="mini" icon="el-icon-minus" @click="removeMetaItem(meta.tempId)" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item v-if="menuType == 3" prop="permissionValue" label="权限标识" size="normal">
          <el-input v-model="menu.permissionValue" type="textarea" placeholder="按钮权限标识,比如: productList.list" size="normal" clearable />
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button size="small" @click="handleClose">取消</el-button>
        <el-button size="small" type="primary" @click="doSave">确定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

import _ from 'lodash'
import permissionApi from '@/api/auth/permission'
export default {
    name: 'MenuForm',
    props: {
        options: {
            type: Array,
            required: true
        }
    },
    data() {
        return {
            dialog: false,
            menuType: 1, // 选择菜单的类型
            menu: {
                sort: 0
            },
            menuTree: [],
            metaList: [{
                key: 'title',
                value: '未命名'
            }], // meta属性列表
            rules: {
                'title': [
                    { required: true, message: '标题不能为空', trigger: 'blur' }
                ],
                'name': [
                    { required: true, message: 'name不能为空', trigger: 'blur' }
                ],
                'path': [
                    { required: true, message: '路径不能为空', trigger: 'blur' }
                ],
                'component': [
                    { required: true, message: '组建不能为空', trigger: 'blur' }
                ],
                'permissionValue': [
                    { required: true, message: '权限标识不能为空', trigger: 'blur' }
                ]
            }
        }
    },
    computed: {
        optionsCom() {
            // 去掉空children 并且禁止最后一项
            var menus = _.cloneDeep(this.options)
            this.rebuildMenuTree(menus)
            return menus
        }
    },
    created() {
        // 初始化menuTree

    },
    methods: {
        openDialog() {
            this.dialog = true
        },
        handleClose() {
            this.dialog = false
        },
        doSave() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    var rsMenu = {}
                    // 获取menuTree值
                    var menuSelNodes = this.$refs.menuTree.getCheckedNodes()
                    if (menuSelNodes && menuSelNodes.length > 0) {
                        // 因为id被覆盖 变成了value
                        rsMenu.pId = menuSelNodes[0].value
                        rsMenu.level = menuSelNodes[0].level + 1
                        console.log(menuSelNodes)
                    }
                    if (this.menuType === 1) {
                        // 合并属性
                        Object.assign(this.menu, rsMenu)
                        // 设置pid属性
                        this.menu.pId = '0'
                        delete rsMenu.title
                        delete rsMenu.permissionValue
                    } else if (this.menuType === 2) {
                        if (!this.menu.pId) {
                            this.$message.error('父类菜单必选!')
                            return
                        }
                        Object.assign(this.menu, rsMenu)

                        delete rsMenu.title
                        delete rsMenu.permissionValue
                    } else {
                        // 按钮类型
                        rsMenu = {
                            type: 2,
                            pId: this.menu.pId,
                            title: this.menu.title,
                            sort: this.menu.sort,
                            permissionValue: this.menu.permissionValue
                        }
                    }
                    // 再次构建 设置meta
                    if (this.menuType != 3) {
                        rsMenu.type = 1
                        for (var i = 0; i < this.metaList.length; i++) {
                            var item = this.metaList[i]
                            if (item.key || item.value) {
                                if (!rsMenu.meta) {
                                    rsMenu.meta = {}
                                }
                                rsMenu.meta[item.key] = item.value
                            }
                        }
                        if (rsMenu.meta) {
                            rsMenu.title = rsMenu.meta.title
                            // 后台接收字符串类型meta 必须是json格式
                            rsMenu.meta = JSON.stringify(rsMenu.meta)
                        }
                    }
                    console.log(rsMenu)
                    permissionApi.savePermission(rsMenu)
                        .then(res => {
                            if (res.success) {
                                this.$message.success('保存成功!')
                            } else {
                                this.$message.error(res.message)
                            }
                        })
                } else {
                    this.$message.error('请注意表单验证!')
                    return false
                }
            })
        },
        menuTreeChange(v) {
            console.log(v)
        },
        rebuildMenuTree(menus) {
            for (var i = 0; i < menus.length; i++) {
                var item = menus[i]
                if (item.type == 2) {
                    item.disabled = true
                }
                if (item.children && item.children.length == 0) {
                    delete item.children
                } else {
                    this.rebuildMenuTree(item.children)
                }
            }
        },
        createMetaItem() {
            this.metaList.push({
                tempId: new Date().getTime(),
                key: '',
                value: ''
            })
        },
        removeMetaItem(tempId) {
            this.metaList = this.metaList.filter(item => item.tempId != tempId)
        }
    }
}
</script>
<style lang="scss" scoped>
    .menu-form{

    }
</style>
